/**
 * 445. 两数相加 II
 */
public class No445 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode pre1 = null, cur1 = l1, nex1;
        int len1 = 0, len2 = 0;
        while (cur1 != null) {
            nex1 = cur1.next;
            cur1.next = pre1;
            pre1 = cur1;
            cur1 = nex1;
            len1++;
        }
        ListNode pre2 = null, cur2 = l2, nex2;
        while (cur2 != null) {
            nex2 = cur2.next;
            cur2.next = pre2;
            pre2 = cur2;
            cur2 = nex2;
            len2++;
        }
        ListNode temp1 = pre1, temp2 = pre2, sent = new ListNode(-1);
        if (len1 < len2) {
            temp1 = pre2;
            temp2 = pre1;
        }
        sent.next = temp1;
        while (temp1 != null || temp2 != null) {
            if (temp1 == null) {
                temp1 = new ListNode(0);
            }
            if (temp2 == null) {
                temp2 = new ListNode(0);
            }
            temp1.val += temp2.val;
            temp1 = temp1.next;
            temp2 = temp2.next;
        }
        ListNode pre3 = null, cur3 = sent.next, nex3;
        while (cur3 != null) {
            if (cur3.val >= 10) {
                cur3.val %= 10;
                if (cur3.next == null) {
                    cur3.next = new ListNode(0);
                }
                cur3.next.val++;
            }
            nex3 = cur3.next;
            cur3.next = pre3;
            pre3 = cur3;
            cur3 = nex3;
        }
        return pre3;
    }
}
